<template>
    <van-address-edit
        :area-list="areaList"
        show-delete
        show-set-default
        show-search-result
        :address-info="AddressInfo"
        :area-columns-placeholder="['请选择', '请选择', '请选择']"
        @save="OnSave"
        @delete="OnDelete"
    />
</template>

<script setup>
// 引入地区数据
import { areaList } from '@vant/area-data';

const { proxy } = getCurrentInstance();

const business = proxy.$business;

// 接收地址栏的参数
const AddrId = ref(proxy.$route.query.addrid ?? 0);

// 初始数据
const AddressInfo = ref({});

onBeforeMount(() => GetAddressInfo());

const GetAddressInfo = async () =>
{
    let params = {
        busid:business.value.id,
        addrid:AddrId.value
    }

    let result = await proxy.$http.post({
        url:'/address/info',
        params
    })

    if(result.code === 1)
    {
        let info = result.data;

        AddressInfo.value = {
            name:info.consignee,
            tel:info.mobile,
            areaCode:info.district ? info.district : (info.city ? info.city : info.province),
            addressDetail:info.address,
            isDefault:info.status == 1 ? true : false
        }
    }else{
        proxy.$fail({
            message:result.msg,
            onClose:() =>
            {
                proxy.$router.back();
            }
        });
    }
}

const OnSave = async(value) =>
{
    let params = {
        busid:business.value.id,
        id:AddrId.value,
        consignee:value.name,
        mobile:value.tel,
        code:value.areaCode,
        address:value.addressDetail,
        status:value.isDefault === true ? 1 : 0
    }

    let result = await proxy.$http.post({
        url:'/address/edit',
        params
    })

    if(result.code === 1)
    {
        proxy.$success({
            message:result.msg,
            onClose:() =>
            {
                proxy.$router.back();
            }
        })
    }else{
        proxy.$fail(result.msg);
    }
}

const OnDelete = () =>
{
    proxy.$confirm({
        title:'删除',
        message:'是否确认删除收货地址？'
    }).then(async () =>
    {
        let params = {
            busid:business.value.id,
            addrid:AddrId.value
        }

        let result = await proxy.$http.post({
            url:'/address/del',
            params
        })

        if(result.code === 1)
        {
            proxy.$success({
                message:result.msg,
                onClose:() =>
                {
                    proxy.$router.back();
                }
            })
        }else{
            proxy.$fail(result.msg);
        }
    }).catch((err) => {});
}
</script>